package com.definesys.smecrailtransit.module.RealTime;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;

import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.definesys.smecrailtransit.R;
import com.definesys.smecrailtransit.api.SmecRailConstant;
import com.definesys.smecrailtransit.base.SmecBaseFragment;

import com.definesys.smecrailtransit.databinding.FragmentRealTimeBinding;
import com.definesys.smecrailtransit.module.RealTime.RealTimeAdapter.RealTimeAdapter;
import com.definesys.smecrailtransit.module.RealTime.bean.RealTimeBean;
import com.definesys.smecrailtransit.utils.CommonUtils;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.footer.LoadingView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import jp.wasabeef.recyclerview.animators.SlideInLeftAnimator;

import static com.definesys.smecrailtransit.MainActivity.JPUSH_REFRESH;
import static com.definesys.smecrailtransit.MainActivity.WAY_TO_FRAGMNET;


/**
 * Created by xupeizuo on 2017/7/20.
 */

public class RealTimeFragment extends SmecBaseFragment<RealTimePresenter> implements RealTimeContract{

    public static final String GET_REAL_TIME_HEADER_SCUUESS="getRealTimeHeaderSuccess";
    public static final String GET_REAL_TIME_FAILURE="getRealTimeFailure";

    private HashMap<String,String> map=new HashMap<>();
    private SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private Handler handler=new Handler();
    private boolean isloadMore=false;

    @Override
    protected RealTimePresenter getPersenter() {
        return new RealTimePresenter(getActivity());
    }

    private FragmentRealTimeBinding fragmentRealTimeBinding;
    private RealTimeAdapter realTimeAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentRealTimeBinding=DataBindingUtil.inflate(inflater, R.layout.fragment_real_time,container,false);
        _initView();
        return fragmentRealTimeBinding.getRoot();
    }

    private void _initView(){
        realTimeAdapter=new RealTimeAdapter();
        fragmentRealTimeBinding.recyclerView.setItemAnimator(SmecRailConstant.getSlideInLeftAnimator());
        fragmentRealTimeBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        fragmentRealTimeBinding.recyclerView.setAdapter(realTimeAdapter);
        realTimeAdapter.setTimeBeanArrayList(getRealTimeBeanFromRealm());
        fragmentRealTimeBinding.refreshLayout.setHeaderView(SmecRailConstant.getSinaRefreshView());
        fragmentRealTimeBinding.refreshLayout.setBottomView(new LoadingView(getContext()));
        fragmentRealTimeBinding.refreshLayout.setAutoLoadMore(true);
        fragmentRealTimeBinding.refreshLayout.setEnableOverScroll(false);
        fragmentRealTimeBinding.refreshLayout.setEnableLoadmore(false);

        fragmentRealTimeBinding.refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                String from="";
                String to="";
                if(CommonUtils.notEmpty(realTimeAdapter.getTimeBeanArrayList())&&realTimeAdapter.getTimeBeanArrayList().size()>1){
                    from=(realTimeAdapter.getTimeBeanArrayList().get(1).getEndDate()!=null &&
                            !realTimeAdapter.getTimeBeanArrayList().get(1).getEndDate().equals("") )?
                            realTimeAdapter.getTimeBeanArrayList().get(1).getEndDate() : realTimeAdapter.getTimeBeanArrayList().get(1).getBeginDate();
                }else {
                    to=simpleDateFormat.format(new Date());
                }
                map.put("from",from);
                map.put("to",to);
                isloadMore=false;
                getRealTime(map);
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                String from="";
                String to="";
                if(CommonUtils.notEmpty(realTimeAdapter.getTimeBeanArrayList())&&realTimeAdapter.getTimeBeanArrayList().size()>1){
                    to=realTimeAdapter.getTimeBeanArrayList().get(realTimeAdapter.getTimeBeanArrayList().size()-1).getBeginDate();
                }else {
                    to=simpleDateFormat.format(new Date());
                }
                map.put("from",from);
                map.put("to",to);
                isloadMore=true;
                getRealTime(map);
            }

        });

    }

    public static RealTimeFragment newInstance() {
        Bundle args = new Bundle();
        RealTimeFragment fragment = new RealTimeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void getRealTime(HashMap<String, String> map) {
        mPresenter.getRealTime(map);
    }

    @Override
    public ArrayList<RealTimeBean> getRealTimeBeanFromRealm() {
        return mPresenter.getRealTimeBeanFromRealm();
    }

    /**
     * 保存最新数据至数据库
     * @param arrayList
     */
    @Override
    public void saveDataToRealm(ArrayList<RealTimeBean> arrayList) {
        mPresenter.saveDataToRealm(arrayList);
    }

    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(GET_REAL_TIME_HEADER_SCUUESS)
            }
    )
    public void getGetRealTimeScuuess(ArrayList<RealTimeBean> arrayList){
        if(isloadMore){
            realTimeAdapter.addFooter(arrayList);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    fragmentRealTimeBinding.refreshLayout.finishLoadmore();
                    saveDataToRealm(realTimeAdapter.getTimeBeanArrayList());
                }
            },2000);
        }else {
            realTimeAdapter.addHeader(arrayList);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    fragmentRealTimeBinding.refreshLayout.finishRefreshing();
                    fragmentRealTimeBinding.refreshLayout.setEnableLoadmore(true);
                    saveDataToRealm(realTimeAdapter.getTimeBeanArrayList());
                }
            },1000);
        }

    }

    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(GET_REAL_TIME_FAILURE)
            }
    )
    public void getGetRealTimeFailure(Object o){
        if(isloadMore){
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    fragmentRealTimeBinding.refreshLayout.finishLoadmore();
                }
            },1500);
        }else {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    fragmentRealTimeBinding.refreshLayout.finishRefreshing();
                }
            },1000);
        }
    }

    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(JPUSH_REFRESH)
            }
    )
    public void jpushRefres(Object o){
        fragmentRealTimeBinding.refreshLayout.startRefresh();
    }


    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(WAY_TO_FRAGMNET)
            }
    )
    public void refresh(String position){
        if(position.equals("0")){
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    fragmentRealTimeBinding.refreshLayout.startRefresh();
                }
            },100);
        }
    }
}
